﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using Engine.Terrain;
using Microsoft.Xna.Framework;

namespace Engine
{
    public class WorldLoader:IWorldLoader
    {
        public World Load(Game game,string path)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            World world;
            using (Stream stream = File.Open(path, FileMode.Open))
            {
                world=(World)binaryFormatter.Deserialize(stream);

                using (Stream terrainStream = File.Open(GetTerrainPath(path), FileMode.Open))
                {
                    world.Terrain=(HeightMapTerrain)binaryFormatter.Deserialize(terrainStream);
                }
            } 
            world.StaticObjects.ForEach(w=>w.ReloadModel(game));
            world.Game = game;
            return world;
        }
        public void Save(World world, string path)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (Stream stream = File.Open(path, FileMode.OpenOrCreate))
            {
                binaryFormatter.Serialize(stream, world);
                
                using (Stream terrainStream = File.Open(GetTerrainPath(path), FileMode.OpenOrCreate))
                {
                    binaryFormatter.Serialize(terrainStream,world.Terrain);
                }
            } 
        }
        private string GetTerrainPath(string mapPath)
        {
            string pathWithoutExtension=Path.Combine(Path.GetDirectoryName(mapPath), Path.GetFileNameWithoutExtension(mapPath));
            string terrainPath = string.Format("{0}_terrain.ter",pathWithoutExtension);
            return terrainPath;
        }
    }
}
